/**
 * @Title: HomeActivity.java
 * @Package com.sinoglobal.waitingMe.activity
 * @Description: TODO(用一句话描述该文件做什么)
 * @author hpq
 * @date 2015-8-30 上午11:55:09
 */

package com.sinoglobal.wallet.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.sinoglobal.wallet.R;
import com.sinoglobal.wallet.api.RemoteImpl;
import com.sinoglobal.wallet.app.SinoConstans;
import com.sinoglobal.wallet.entity.RsAplipay;
import com.sinoglobal.wallet.entity.RsUpay;
import com.sinoglobal.wallet.entity.RsWechat;
import com.sinoglobal.wallet.entity.W_OrderStateEntiy;
import com.sinoglobal.wallet.task.MyAsyncTask;
import com.sinoglobal.wallet.util.ActivityUtil;
import com.sinoglobal.wallet.util.LogUtils;
import com.sinoglobal.wallet.util.NetWorkUtil;
import com.sinoglobal.wallet.util.PayResult;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umpay.quickpay.UmpPayInfoBean;
import com.umpay.quickpay.UmpayQuickPay;
/**
 * @author clf
 * @createdate 2015-11-7
 * @Description: TODO(充值详情)
 */
public class W_RechargeDetailsActivity extends W_SinoBaseActivity {
	private TextView recharge_condition_txt,recharge_details_time,recharge_condtion_txt,recharge_detail_paystyle_recordname,recharge_state_notice,recharge_detail_paystyle_name,recharge_detail_commmit,recharge_detail_money;
	private  ImageView recharge_sucess_img;
	int payStyle=0 ;
	private int payState;
	  private static final int SDK_PAY_FLAG = 1; //支付宝支付用的判断标记
		private MyHandler myHandler;//支付宝支付信息回调 使用静态内部类是防止内存泄露
		private String isRecharge="-1";//1,充值成功。0，充值失败。2待充值,3,提交成功
		private RsAplipay aplipay;//获取的支付订单对象
		private String Type="1";//充值界面跳转到充值详情的标示1是充值界面跳过去。2是充值记录界面跳过去
		private String money;
		private RsWechat wechat;
		private RsUpay upay;
		private IWXAPI api;
		private DestoryRechargeDetailsReciver destoryRechargeDetailsReciver;//微信回调接口通过这个广播可以销毁该W_RechargeDetailsActivity
		private String source="";
		/** 请求返回码 **/
		public static final int REQUESTCODE = 10;
		/** 优付支付成功 **/
		private static final String UMPAY_SUCCESS = "0000";
		/** 优付支付取消 **/
		private static final String UMPAY_CANCEL = "1001";
		
		private class MyHandler extends Handler {


	        public void handleMessage(Message msg) {
	            switch (msg.what) {
	                case SDK_PAY_FLAG: {
	                    PayResult payResult = new PayResult((String) msg.obj);
	                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
	                    String resultInfo = payResult.getResult();

	                    //支付状态
	                    String resultStatus = payResult.getResultStatus();
	                //	Toast.makeText(W_RechargelActivity.this, "支付宝返回码=="+resultStatus, 0).show();
	                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
	                    if (TextUtils.equals(resultStatus, "9000")) {
	                       // notifyServer();通知故服务器支付成功
	                       // showToast(getString(R.string.pay_success));
	                    	isRecharge="1";
	                    	
	                    	getOrderState(aplipay.getTrade_sn());
	                    	break;
	                    }
	                    // 判断resultStatus 为非“9000”则代表可能支付失败
	                    // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
	                    else if (TextUtils.equals(resultStatus, "8000")) {
	                       // showToast(getString(R.string.pay_confirming));
	                      	isRecharge="3";
	                      	
	                    } else if (TextUtils.equals(resultStatus, "6001")) {
	                     //   showToast(getString(R.string.pay_confirming));
	                      	isRecharge="2";
	                    } else if (TextUtils.equals(resultStatus, "6002")) {
	                       // showToast(getString(R.string.pay_confirming));
	                    	if("Record".equals(source)){
	        					sendDestoryRRDBroadcast();
	        				}
	                        Toast.makeText(W_RechargeDetailsActivity.this, "网络状态不佳，请稍侯！", 0).show();
	                    	return;
	                    }else {
	                        // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
	                      //  showToast(getString(R.string.pay_fail));
	                    	isRecharge="0";
	                        
	                    } 
	                	if("Record".equals(source)){
        					sendDestoryRRDBroadcast();
        				}
	                    Bundle bundle = new Bundle();
	        			bundle.putString("isRecharge", isRecharge);
	        			bundle.putString("Money", money);
	        			bundle.putString("Source", source);//通知下个页面是从记录页面传过来的数据
	        			bundle.putSerializable("Sing", aplipay);//支付宝签名
	        			 bundle.putInt("payStyle", payStyle);
	        			goIntent(W_RechargeDetailsActivity.class, bundle); 	
	                             finish();
	                    break;
	                }
	            }
	        }
	    }
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.wallet_rechargedetail_layout);
		mTemplateTitleText.setText("充值");
		api = WXAPIFactory.createWXAPI(this, null);
		// 将该app注册到微信
		api.registerApp(SinoConstans.APP_WeCHATID);
		initView();
		initReciver();
		source = getIntent().getStringExtra("Source");
		 isRecharge = getIntent().getStringExtra("isRecharge");
		  payStyle = getIntent().getIntExtra("payStyle", -1);
		  money = getIntent().getStringExtra("Money");
		  if(money!=null){
		   float  moneyFouble= Float.valueOf(money);
		  recharge_detail_money.setText(String.format("%.2f", moneyFouble)+"元");  }
			  setPayStyle();
			  if("0".equals(isRecharge)){
					recharge_sucess_img.setImageDrawable(getResources().getDrawable(R.drawable.pay_icon_failure));
					recharge_condtion_txt.setText("充值失败，请重试!");
					recharge_condtion_txt.setTextColor(getResources().getColor(R.color.w_recharge_red));
					recharge_detail_commmit.setText("重试");
				}else if("1".equals(isRecharge)){
					recharge_sucess_img.setImageDrawable(getResources().getDrawable(R.drawable.pay_icon_success));
					recharge_condtion_txt.setTextColor(getResources().getColor(R.color.w_recharge_green));
					recharge_condtion_txt.setText("充值成功!");
					recharge_detail_commmit.setText("完成");
					
				}else  if("2".equals(isRecharge)){
					recharge_sucess_img.setImageDrawable(getResources().getDrawable(R.drawable.pay_icon_warn));
				recharge_condtion_txt.setTextColor(getResources().getColor(R.color.w_recharge_yellow));
				recharge_condtion_txt.setText("待充值!");
				recharge_detail_commmit.setText("去支付");
			}else  if("3".equals(isRecharge)){
				recharge_sucess_img.setImageDrawable(getResources().getDrawable(R.drawable.pay_icon_submit));
				recharge_condtion_txt.setTextColor(getResources().getColor(R.color.w_recharge_green));
				recharge_condtion_txt.setText("提交成功!");
				recharge_detail_commmit.setText("返回");
			}
			}
		
		
   public void setPayStyle(){
	    if(payStyle==1){
			recharge_detail_paystyle_name.setText("余额");
		}else if(payStyle==2){
			aplipay= (RsAplipay) getIntent().getSerializableExtra("Sing");
			recharge_detail_paystyle_name.setText("支付宝");
		}else if(payStyle==3){
			recharge_detail_paystyle_name.setText("借记卡");
			upay= (RsUpay) getIntent().getSerializableExtra("Upay");
		}else if(payStyle==4){
			wechat= (RsWechat) getIntent().getSerializableExtra("WeChat");
			recharge_detail_paystyle_name.setText("微信");
		}		
	
   }  


	private void initView() {
	    myHandler=new MyHandler();
		recharge_condition_txt =findView(R.id.recharge_condtion_txt);
		recharge_sucess_img = findView(R.id.recharge_sucess_img);
		recharge_condtion_txt = findView(R.id.recharge_condtion_txt);
		recharge_detail_paystyle_recordname = findView(R.id.recharge_detail_paystyle_recordname);
		recharge_details_time = findView(R.id.recharge_details_time);
		recharge_detail_paystyle_name = findView(R.id.recharge_detail_paystyle_name);
		recharge_detail_commmit = findView(R.id.recharge_detail_commmit);
		recharge_detail_money = findView(R.id.recharge_detail_money);
		recharge_detail_commmit.setOnClickListener(this);
		mTemplateLeftImg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if("Record".equals(source)){
					String orderSn = "";
					  if(payStyle==2){
						 orderSn=aplipay.getTrade_sn();
						}else if(payStyle==3){
							 orderSn=upay.getTrade_sn();
						}else if(payStyle==4){
						 orderSn=wechat.getTrade_sn();
						}		
					updateRechargeRecordBroadcast(isRecharge,orderSn);
					
					finish();
				}else{
					  exit();
					    Intent intent = new Intent(W_RechargeDetailsActivity.this,W_HomeActivity.class);
					    startActivity(intent);	}
			
			}
		});
	
	}
	private void updateRechargeRecordBroadcast(String isRecharge,String orderSn) {
		Intent intent = new Intent();
		intent.setAction(SinoConstans.KEY_UpdateReceiver);
		intent.putExtra("isRecharge",isRecharge);
		intent.putExtra("orderSn",orderSn);
		sendBroadcast(intent);
	}
	/**
	 * 销毁该acivtiy的广播
	 */
	private void initReciver() {
		// TODO Auto-generated method stub
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(SinoConstans.KEY_DestoryReceiver);
		destoryRechargeDetailsReciver = new DestoryRechargeDetailsReciver();
		registerReceiver(destoryRechargeDetailsReciver, intentFilter);
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		if(id==R.id.recharge_detail_commmit){
			if(recharge_detail_commmit.getText().equals("完成")){
				if("Record".equals(source)){
					String orderSn = "";
					  if(payStyle==2){
						 orderSn=aplipay.getTrade_sn();
						}else if(payStyle==3){
							 orderSn=upay.getTrade_sn();
						}else if(payStyle==4){
						 orderSn=wechat.getTrade_sn();
						}		
					updateRechargeRecordBroadcast(isRecharge,orderSn);
					
					finish();
				}else{
					  exit();
					    Intent intent = new Intent(W_RechargeDetailsActivity.this,W_HomeActivity.class);
					    startActivity(intent);	}
				    }
			if(recharge_detail_commmit.getText().equals("重试")){
				if(payStyle==2){//支付宝支付
					pay(aplipay.getSign());
				}else if(payStyle==3){//U付,借记卡支付	
					doUmpay(upay.getTrade_no());
				}else if(payStyle==4){//微信支付
					boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
					
					if(ActivityUtil.checkApkExist(this,"com.tencent.mm")){
						if(isPaySupported){
							PayReq req = new PayReq();
							req.appId			= wechat.getAppId();
							req.partnerId		= wechat.getPartnerid();
							req.prepayId		= wechat.getPrepayid();
							req.nonceStr		= wechat.getNoncestr();
							req.timeStamp		= wechat.getTimestamp();
							req.packageValue	="Sign=WXPay";
							 req.sign			= wechat.getSign();
						//	LogUtils.v("appId=="+	req.appId+"partnerId=="+req.partnerId+"prepayId=="+req.prepayId+"nonceStr=="+req.nonceStr+"timeStamp=="+req.timeStamp+"packageValue=="+req.packageValue+"sign==="+req.sign	);
							// 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
							sendWeChatBroadcast(wechat,money,"wallet");
						}else{
							Toast.makeText(this, "当前微信版本不支持支付！", 0).show();
						}
					
					}else{
						Toast.makeText(this, "请先安装微信！", 0).show();
					}
				
				}
			}
			if(recharge_detail_commmit.getText().equals("去支付")){
				if(payStyle==2){//支付宝支付
					pay(aplipay.getSign());
				}else if(payStyle==3){//U付	
					doUmpay(upay.getTrade_no());
				}else if(payStyle==4){//微信支付
					
	boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
					
					if(ActivityUtil.checkApkExist(this,"com.tencent.mm")){
						if(isPaySupported){
							PayReq req = new PayReq();
							req.appId			= wechat.getAppId();
							req.partnerId		= wechat.getPartnerid();
							req.prepayId		= wechat.getPrepayid();
							req.nonceStr		= wechat.getNoncestr();
							req.timeStamp		= wechat.getTimestamp();
							req.packageValue	="Sign=WXPay";
							 req.sign			= wechat.getSign();
							//LogUtils.v("appId=="+	req.appId+"partnerId=="+req.partnerId+"prepayId=="+req.prepayId+"nonceStr=="+req.nonceStr+"timeStamp=="+req.timeStamp+"packageValue=="+req.packageValue+"sign==="+req.sign	);
						
							// 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
							api.sendReq(req);
							sendWeChatBroadcast(wechat,money,"wallet");//传到微信的回调页面WXPayEntryActivity
						}else{
							Toast.makeText(this, "当前微信版本不支持支付！", 0).show();
						}
					
					}else{
						Toast.makeText(this, "请先安装微信！", 0).show();
					}
				}
				}
			if(recharge_detail_commmit.getText().equals("返回")){
				if("Record".equals(source)){
					String orderSn = "";
					  if(payStyle==2){
						 orderSn=aplipay.getTrade_sn();
						}else if(payStyle==3){
							 orderSn=upay.getTrade_sn();
						}else if(payStyle==4){
						 orderSn=wechat.getTrade_sn();
						}		
					updateRechargeRecordBroadcast(isRecharge,orderSn);
					
					finish();
				}else{
					  exit();
					    Intent intent = new Intent(W_RechargeDetailsActivity.this,W_HomeActivity.class);
					    startActivity(intent);	}
			
			}else if (id == R.id.wallet_noData) {
				 if(NetWorkUtil.getNetWorkInfoType(getApplicationContext())==NetWorkUtil.NONE){
						showToast("请检查网络是否连接！");	
						 loadError(true);
						}else{
							loadError(false);;
						}
			} 
		}
	}
	private void sendWeChatBroadcast(RsWechat rs,String str,String type) {
		Intent intent = new Intent();
		intent.setAction(SinoConstans.KEY_WechatReceiver);
		intent.putExtra("WeChat",rs);
		intent.putExtra("Money",str);
		intent.putExtra("Type",type);
		intent.putExtra("Source",source);//记录是从充值记录页面传的数据
		sendBroadcast(intent);
	}
	  /**
     * U付支付
     *
     * @param tradeNo 封装数据
     */
    private void doUmpay(String tradeNo) {
        UmpayQuickPay.requestPayWithBind(this, tradeNo, null, "0", null, new UmpPayInfoBean(), REQUESTCODE);//借记卡支付
    }
    /**
     * 支付宝支付
     *
     * @param orderInfo签名串
     */
	public void pay(final String orderInfo) {
		Runnable payRunnable = new Runnable() {
			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(W_RechargeDetailsActivity.this);
				// 调用支付接口
				String result = alipay.pay(orderInfo);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				myHandler.sendMessage(msg);
			}
		};
		   // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

		 
	}
	private void getOrderState(final String orderSn) {
		MyAsyncTask<W_OrderStateEntiy> task = new MyAsyncTask<W_OrderStateEntiy>(true,this,true) {
			@Override
			public W_OrderStateEntiy before(Void... params) throws Exception {
				// TODO 测试接口
				return RemoteImpl.getInstance().getOrderState(W_RechargeDetailsActivity.this,orderSn);
			}
			
			@Override
			public void after(W_OrderStateEntiy result) {
				if (result != null) {
					if (result.getCode().equals("100")) {
					String	 orderState=result.getRs();
					 if("3".equals(orderState)){//支付订单状态1：支付中、2：已回调、3：支付成功、4：异常订单
							isRecharge="1";
					  }else {
							isRecharge="3";
					  }
					 if("Record".equals(source)){
     					sendDestoryRRDBroadcast();
     				}
						    Bundle bundle = new Bundle();
		        			bundle.putString("isRecharge", isRecharge);
		        			bundle.putString("Money", money);
		        			bundle.putString("Source", source);//通知下个页面是从记录页面传过来的数据
		        			 bundle.putInt("payStyle", payStyle);
		        			 bundle.putSerializable("Sing", aplipay);//支付宝签名
		        			 bundle.putSerializable("Upay", upay);//支付宝签名
		        			goIntent(W_RechargeDetailsActivity.class, bundle);
		        			finish();
					}else{
						if("Record".equals(source)){
        					sendDestoryRRDBroadcast();
        				}
						Toast.makeText(W_RechargeDetailsActivity.this, "订单状态查询失败", 0).show();
						 Bundle bundle = new Bundle();
		        			bundle.putString("isRecharge", isRecharge);
		        			bundle.putString("Money", money);
		        			bundle.putString("Source", source);//通知下个页面是从记录页面传过来的数据
		        			 bundle.putSerializable("Sing", aplipay);//支付宝签名
		        			 bundle.putSerializable("Upay", upay);//支付宝签名
		        			 bundle.putInt("payStyle", 2);
		        			goIntent(W_RechargeDetailsActivity.class, bundle);
		        			finish();
					}
				}
				
			}
			
			@Override
			public void exception() {
			}
		};
		task.execute();
	}
	/**
	 * 3.U付在这里接收并处理支付结果
	 * 
	 * @param requestCode
	 *            支付请求码
	 * @param resultCode
	 *            SDK固定返回88888
	 * @param data
	 *            支付结果和结果描述信息
	 * @author niexuyang 2012-8-20
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUESTCODE) {
			String umpresultCode = data.getStringExtra("umpResultCode");
			if (UMPAY_SUCCESS.equals(umpresultCode)) {
				showToast("支付成功");
				isRecharge="1";
				if("Record".equals(source)){
					sendDestoryRRDBroadcast();
				}
            	getOrderState(upay.getTrade_sn());	
			} else if (UMPAY_CANCEL.equals(umpresultCode)) {
				showToast("取消支付");
				isRecharge="2";
				if("Record".equals(source)){
					sendDestoryRRDBroadcast();
				}
				  Bundle bundle = new Bundle();
      			bundle.putString("isRecharge", isRecharge);
      			bundle.putString("Money", money);
      			bundle.putString("Source", source);//通知下个页面是从记录页面传过来的数
      			bundle.putSerializable("Upay", upay);//U付订单对象
      			 bundle.putInt("payStyle", payStyle);
      			goIntent(W_RechargeDetailsActivity.class, bundle); 	
      			finish();
			} else {
				showToast("支付失败");
				isRecharge="0";
				if("Record".equals(source)){
					sendDestoryRRDBroadcast();
				}
				  Bundle bundle = new Bundle();
      			bundle.putString("isRecharge", isRecharge);
      			bundle.putString("Money", money);
      			bundle.putString("Source", source);//通知下个页面是从记录页面传过来的数
      			bundle.putSerializable("Upay", upay);//U付订单对象
      			 bundle.putInt("payStyle", payStyle);
      			goIntent(W_RechargeDetailsActivity.class, bundle); 	
      			finish();
			}
			super.onActivityResult(requestCode, resultCode, data);
		}
	}
	private void sendDestoryRRDBroadcast() {//发送销毁W_RechargeRecordDetailsActivity的广播
		Intent intent = new Intent();
		intent.setAction(SinoConstans.KEY_DestoryReceiverTwo);
		sendBroadcast(intent);
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(destoryRechargeDetailsReciver);//充值详情的广播取消
		  if (myHandler != null) { //退出时清空handler所有队列信息,以防内存泄露
	            myHandler.removeCallbacksAndMessages(null);
	        }
	}
	public  class DestoryRechargeDetailsReciver extends BroadcastReceiver {


		public  DestoryRechargeDetailsReciver(){

		}

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(SinoConstans.KEY_DestoryReceiver)){
				W_RechargeDetailsActivity.this.finish();
				//LogUtils.v("DestoryRechargeDetailsReciver-----");
			}

		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if("Record".equals(source)){
			String orderSn = "";
			  if(payStyle==2){
				 orderSn=aplipay.getTrade_sn();
				}else if(payStyle==3){
					 orderSn=upay.getTrade_sn();
				}else if(payStyle==4){
				 orderSn=wechat.getTrade_sn();
				}		
			updateRechargeRecordBroadcast(isRecharge,orderSn);
			
			finish();
		}else{
			  exit();
			    Intent intent = new Intent(W_RechargeDetailsActivity.this,W_HomeActivity.class);
			    startActivity(intent);	} 
		return super.onKeyDown(keyCode, event);
	}
}
